import React, { useState, useEffect, useCallback } from 'react';
import { createRoot } from 'react-dom/client';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import { motion, AnimatePresence } from 'framer-motion';
import '../custom/customComponents.css';
import { 
  CheckCircleOutlined, 
  CloseCircleOutlined, 
  InfoCircleOutlined, 
  ExclamationCircleOutlined,
  CloseOutlined
} from '@ant-design/icons';

// 通知类型
export type NotificationType = 'success' | 'error' | 'info' | 'warning';

// 通知配置接口
export interface NotificationConfig {
  id?: string;
  type: NotificationType;
  title?: string;
  message: string;
  duration?: number; // 持续时间，单位毫秒，0表示不自动关闭
  closable?: boolean;
  onClose?: () => void;
}

// 通知实例接口
interface NotificationInstance extends NotificationConfig {
  id: string;
  timestamp: number;
}

// 全局通知管理器
class NotificationManager {
  private static instance: NotificationManager;
  private notifications: NotificationInstance[] = [];
  private listeners: ((notifications: NotificationInstance[]) => void)[] = [];
  private container: HTMLDivElement | null = null;

  private constructor() {}

  static getInstance(): NotificationManager {
    if (!NotificationManager.instance) {
      NotificationManager.instance = new NotificationManager();
    }
    return NotificationManager.instance;
  }

  // 添加通知监听器
  subscribe(listener: (notifications: NotificationInstance[]) => void) {
    this.listeners.push(listener);
    return () => {
      this.listeners = this.listeners.filter(l => l !== listener);
    };
  }

  // 添加通知
  add(config: NotificationConfig): string {
    const id = config.id || `notification_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const notification: NotificationInstance = {
      ...config,
      id,
      timestamp: Date.now()
    };

    this.notifications = [...this.notifications, notification];
    this.notifyListeners();
    
    // 如果设置了持续时间，自动关闭
    if (config.duration !== 0) {
      const timeout = config.duration || 4500;
      setTimeout(() => {
        this.remove(id);
      }, timeout);
    }

    return id;
  }

  // 移除通知
  remove(id: string) {
    const notification = this.notifications.find(n => n.id === id);
    if (notification) {
      if (notification.onClose) {
        notification.onClose();
      }
      this.notifications = this.notifications.filter(n => n.id !== id);
      this.notifyListeners();
    }
  }

  // 清空所有通知
  clear() {
    this.notifications.forEach(notification => {
      if (notification.onClose) {
        notification.onClose();
      }
    });
    this.notifications = [];
    this.notifyListeners();
  }

  // 通知监听器
  private notifyListeners() {
    this.listeners.forEach(listener => listener([...this.notifications]));
  }

  // 创建通知容器
  createContainer() {
    if (!this.container) {
      this.container = document.createElement('div');
      this.container.id = 'custom-notification-container';
      document.body.appendChild(this.container);
    }
    return this.container;
  }

  // 渲染通知组件
  render() {
    if (!this.container) return;

    const root = createRoot(this.container);
    root.render(<NotificationContainer manager={this} />);
  }
}

// 通知容器组件
const NotificationContainer: React.FC<{ manager: NotificationManager }> = ({ manager }) => {
  const [notifications, setNotifications] = useState<NotificationInstance[]>([]);
  const { mode } = useThemeStore();

  useEffect(() => {
    const unsubscribe = manager.subscribe((newNotifications) => {
      setNotifications(newNotifications);
    });

    return () => {
      unsubscribe();
    };
  }, [manager]);

  const handleClose = useCallback((id: string) => {
    manager.remove(id);
  }, [manager]);

  return (
    <div className="notification-container">
      <AnimatePresence>
        {notifications.map((notification) => (
          <motion.div
            key={notification.id}
            initial={{ opacity: 0, y: -50, scale: 0.3 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, scale: 0.5, transition: { duration: 0.2 } }}
            transition={{ type: "spring", stiffness: 500, damping: 30 }}
          >
            <NotificationItem 
              notification={notification} 
              onClose={handleClose}
              mode={mode}
            />
          </motion.div>
        ))}
      </AnimatePresence>
    </div>
  );
};

// 单个通知项组件
const NotificationItem: React.FC<{
  notification: NotificationInstance;
  onClose: (id: string) => void;
  mode: 'light' | 'dark';
}> = ({ notification, onClose, mode }) => {
  const { type, title, message, closable = true } = notification;

  // 获取图标和样式
  const getIconAndStyle = () => {
    switch (type) {
      case 'success':
        return {
          icon: <CheckCircleOutlined />,
          bgColor: mode === 'dark' ? 'bg-[rgba(35,135,85,0.9)]' : 'bg-[rgba(35,135,85,0.9)]',
          borderColor: mode === 'dark' ? 'border-[rgba(35,135,85,0.3)]' : 'border-[rgba(35,135,85,0.3)]',
          iconColor: '#52c41a'
        };
      case 'error':
        return {
          icon: <CloseCircleOutlined />,
          bgColor: mode === 'dark' ? 'bg-[rgba(206,50,50,0.9)]' : 'bg-[rgba(206,50,50,0.9)]',
          borderColor: mode === 'dark' ? 'border-[rgba(206,50,50,0.3)]' : 'border-[rgba(206,50,50,0.3)]',
          iconColor: '#ff4d4f'
        };
      case 'warning':
        return {
          icon: <ExclamationCircleOutlined />,
          bgColor: mode === 'dark' ? 'bg-[rgba(204,137,0,0.9)]' : 'bg-[rgba(204,137,0,0.9)]',
          borderColor: mode === 'dark' ? 'border-[rgba(204,137,0,0.3)]' : 'border-[rgba(204,137,0,0.3)]',
          iconColor: '#faad14'
        };
      case 'info':
      default:
        return {
          icon: <InfoCircleOutlined />,
          bgColor: mode === 'dark' ? 'bg-[rgba(30,80,180,0.9)]' : 'bg-[rgba(30,80,180,0.9)]',
          borderColor: mode === 'dark' ? 'border-[rgba(30,80,180,0.3)]' : 'border-[rgba(30,80,180,0.3)]',
          iconColor: '#1890ff'
        };
    }
  };

  const { icon, bgColor, borderColor, iconColor } = getIconAndStyle();

  // Determine notification item classes
  const getNotificationClasses = () => {
    const classes = ['notification-item', type];
    return classes.join(' ');
  };

  return (
    <div className={getNotificationClasses()}>
      <div 
        className="notification-icon"
        style={{ color: iconColor }}
      >
        {icon}
      </div>
      <div className="notification-content">
        {title && <div className="notification-title">{title}</div>}
        <div className="notification-message">{message}</div>
      </div>
      {closable && (
        <button 
          className="notification-close"
          onClick={() => onClose(notification.id)}
        >
          <CloseOutlined />
        </button>
      )}
      {/* 动画效果 */}
      <div 
        className="notification-shimmer"
        style={{ 
          color: iconColor
        }}
      />
    </div>
  );
};

// 初始化通知管理器
const notificationManager = NotificationManager.getInstance();

// 创建通知容器
if (typeof document !== 'undefined') {
  notificationManager.createContainer();
  notificationManager.render();
}

// 通知API
export const notification = {
  success(config: Omit<NotificationConfig, 'type'>) {
    return notificationManager.add({ ...config, type: 'success' });
  },
  
  error(config: Omit<NotificationConfig, 'type'>) {
    return notificationManager.add({ ...config, type: 'error' });
  },
  
  info(config: Omit<NotificationConfig, 'type'>) {
    return notificationManager.add({ ...config, type: 'info' });
  },
  
  warning(config: Omit<NotificationConfig, 'type'>) {
    return notificationManager.add({ ...config, type: 'warning' });
  },
  
  open(config: NotificationConfig) {
    return notificationManager.add(config);
  },
  
  close(id: string) {
    notificationManager.remove(id);
  },
  
  destroy() {
    notificationManager.clear();
  }
};

export default notification;